import React, { useState, useEffect, useRef } from 'react'
import { CheckBox, Tab, Button, Message, Modal } from '@kedacom/react-next'
import { useGlobalStore } from '@/store/global'
import shallow from 'zustand/shallow'
import { StyledWrap } from './style'
import BasicInfo from './blocks/basicInfo'
import MeetingParams from './blocks/meetingParams'
import MeetingVmp from './blocks/vmp'
import MeetingDcs from './blocks/dcs'
import MeetingLiveVideo from './blocks/liveVideo'
import MeetingAI from './blocks/ai'
import MeetingMix from './blocks/mix'
import MeetingPoll from './blocks/poll'
import MeetingTVWall from './blocks/tvwall'
import { ITab, useCreateContentStore } from './store'
import { useMeetingParamsStore } from './blocks/meetingParams/store'
import { useBasicInfoStore } from './blocks/basicInfo/store'
import AddMtDialog from '@/components/AddMt/main'
import KdPreSettingDialog from './components/KdPreSettingDialog'
import {
	checkData,
	checkScale,
	getAllParams,
	showOverScaleDialogSave,
	transMeetingParamsToTemplateParams,
} from './store.combine'
import {
	fetchCheckExistRoomBookedOrLockedForCurrentPage,
	fetchEditMeeting,
	fetchEditRegularMeeting,
	fetchEditTpl,
	fetchSaveMeeting,
	fetchSaveRegularMeeting,
	fetchSaveTpl,
} from '@/api/create'
import { fetchStatus } from '@/api/global'
import Alert, { Confirm } from '@/components/Alert'
import { fetchMeetingTimeExpired } from '@/api/myMeeting'
import { t } from 'i18next'
import { SaveMeetingParams, SaveTemplateParams } from '@/api/create/interface'
import UserList from './blocks/user'
import { clearLockedRooms, removeRoomData, unLockMeetingRoom } from './blocks/basicInfo/store.room'
import dayjs from '@/plugins/dayjs'

export default function CreateContent() {
	const ref = useRef(null)
	const { user, serverInfo, SWITCH } = useGlobalStore(
		(state) => ({ user: state.user, serverInfo: state.serverInfo, SWITCH: state.SWITCH }),
		shallow
	)

	const { tab, tabData, isTemplate, _isSaveAsTemplate, update } = useCreateContentStore(
		(state) => ({
			tab: state.tab,
			tabData: state.tabData,
			isTemplate: state.isTemplate,
			_isSaveAsTemplate: state._isSaveAsTemplate,
			update: state.update,
		}),
		shallow
	)

	const { meetingType, encryptedSM } = useMeetingParamsStore(
		(state) => ({ meetingType: state.meetingType, encryptedSM: state.encryptedSM }),
		shallow
	)

	useEffect(() => {
		const isSfuMeeting = meetingType === 2
		useCreateContentStore.setState({
			tabData: [
				{
					label: t('基本信息'),
					value: 'basic',
				},
				{
					label: t('会议参数'),
					value: 'params',
				},
				{
					label: t('会议画面合成'),
					value: 'vmp',
				},
				{
					label: t('轮询'),
					value: 'poll',
					hidden: isSfuMeeting,
				},
				{
					label: t('电视墙'),
					value: 'tvwall',
					hidden: !SWITCH.tvwall,
				},
				{
					label: t('混音'),
					value: 'mix',
					hidden: isSfuMeeting,
				},
				{
					label:
						user?.enable_live && user.enable_video && SWITCH.vrs.live && SWITCH.vrs.video
							? t('录像与直播')
							: user?.enable_video && SWITCH.vrs.video
							? t('会议录像')
							: user?.enable_live && SWITCH.vrs.live
							? t('会议直播')
							: t('录播与直播'),
					value: 'vl',
					hidden:
						!user?.enable_vrs ||
						(!SWITCH.vrs.video && !SWITCH.vrs.live) ||
						(!user.enable_live && !user.enable_video) ||
						encryptedSM,
				},
				{
					label: t('数据协作'),
					value: 'dcs',
					hidden: !user?.enable_dcs || isSfuMeeting || !SWITCH.dcs,
				},
				{
					label: 'AI',
					value: 'ai',
					hidden: !(serverInfo?.enable_kis && user?.enable_kis) || !SWITCH.kis.ai,
				},
			],
		})
	}, [user, serverInfo, meetingType, encryptedSM, SWITCH])

	useEffect(() => {
		update({ _container: ref.current })
	}, [])

	const handleCancel = () => {
		if (isTemplate) {
			window.location.href = './template.html'
		} else {
			if (!(serverInfo?.enable_room && user?.enable_kis)) {
				window.location.href = './meetingList.html'
				return
			}
			if (!serverInfo?.stand_alone) {
				const roomData = useBasicInfoStore.getState().roomData
				if (roomData) {
					clearLockedRooms(
						() => {
							window.location.href = './meetingList.html'
						},
						() => {},
						t('您有锁定的会议室，离开会导致会议室被释放，是否继续?')
					)
				} else {
					window.location.href = './meetingList.html'
				}
			} else {
				window.location.href = './meetingList.html'
			}
		}
	}

	const handelSave = () => {
		const callBack = async () => {
			//数据验证
			let m = Message.loading(t('正在检测能否生成会议，请稍候……'))
			let flag = await checkData()
			m.hide()
			if (!flag) return
			if (isTemplate) {
				//保存模板
				saveTpl()
			} else {
				//保存会议
				if (!(useGlobalStore.getState().serverInfo?.enable_room && user?.enable_kis)) {
					checkStartTime()
					return
				}
				const roomData = useBasicInfoStore.getState().roomData
				const meetingMoid = useCreateContentStore.getState().meetingMoid
				const meetingFormKey = useCreateContentStore.getState().meetingFormKey
				if (roomData) {
					//有会议室的保存情况
					if (roomData.status === 3) {
						Confirm(t('您的会议室全部推荐失败，是否继续创建？'), () => {
							checkStartTime()
						})
					} else {
						fetchCheckExistRoomBookedOrLockedForCurrentPage({
							meeting_moid: meetingMoid,
							meeting_form_key: meetingFormKey,
						}).then((res) => {
							if (res.success) {
								if (!res.data) {
									//无会议室
									let m = Modal.alert({
										title: t('提示'),
										content: (
											<div>
												{t('您锁定的会议室已被释放，是否继续创建？')}
												<br />
												<span style={{ color: '#AAA', fontSize: '14px', lineHeight: '23px' }}>
													{t(
														'已在【发言方】,【轮询】,【画面合成】中设置好的会议室，释放后将会失效，请知晓'
													)}
												</span>
											</div>
										),
										okText: t('确定'),
										cancelText: '',
										onOk: () => {
											m.hide()
											checkStartTime()
										},
										onCancel: () => {
											m.hide()
											removeRoomData()
										},
									})
								} else {
									checkStartTime()
								}
							} else {
								Alert(t('检测会议室锁定是否失效出错'))
							}
						})
					}
				} else {
					checkStartTime()
				}
			}
		}
		let type = checkScale()
		if (type === 1) {
			callBack()
		} else {
			showOverScaleDialogSave(callBack)
		}
	}

	const checkStartTime = () => {
		console.log('创建会议检测会议生成时间')
		let m = Message.loading(t('正在验证会议开始时间，请稍候……'))
		const meetingMoid = useCreateContentStore.getState().meetingMoid
		const meetingFormKey = useCreateContentStore.getState().meetingFormKey
		const { day, startTime } = useBasicInfoStore.getState()
		//服务器时间可能会比电脑时间慢，导致后台校验通过，所以前台再和电脑时间校验一遍
		let time = dayjs(day + ' ' + startTime + ':00').tz()
		let nowTime = dayjs()
		if (time.isBefore(nowTime)) {
			m.hide()
			Alert(t('请在当前时间后创建会议'), () => {
				if (meetingMoid && meetingFormKey && serverInfo?.enable_room && user?.enable_kis) {
					unLockMeetingRoom(() => {
						removeRoomData()
					}, true)
				}
			})
			return
		}
		fetchMeetingTimeExpired({ start_time: startTime, day, meeting_moid: meetingMoid })
			.then((res) => {
				m.hide()
				if (res.success) {
					saveMeeting()
				} else {
					if (meetingMoid) {
						Alert(res.description || t('操作失败'), () => {
							if (meetingFormKey && serverInfo?.enable_room && user?.enable_kis) {
								unLockMeetingRoom(() => {
									removeRoomData()
								}, true)
							}
						})
					} else {
						Alert(res.description || t('操作失败'))
					}
				}
			})
			.catch(() => {
				m.hide()
			})
	}

	const saveMeeting = () => {
		fetchStatus(async () => {
			let m = Message.loading(t('正在保存会议，请稍候……'))
			let data = getAllParams() as SaveMeetingParams
			const { meetingFormKey, meetingMoid, preKey, _isSaveAsTemplate } = useCreateContentStore.getState()
			const repeat = useBasicInfoStore.getState().repeat
			const callback = (
				res: FetchUse<{
					conf_id: string
					meeting_id: string
					machine_room_moid: string
				}>
			) => {
				m.hide()
				if (res.success) {
					Message.info(t('会议保存成功'))
					if (_isSaveAsTemplate) {
						let n = Message.loading(t('正在保存为模板，请稍候……'))
						let templateData = transMeetingParamsToTemplateParams(data)
						fetchSaveTpl(preKey, templateData).then(() => {
							n.hide()
							useCreateContentStore.setState({ meetingFormKey: '' })
							window.location.href = './meetingList.html?scrollTo=' + res.meeting_id
						})
					} else {
						useCreateContentStore.setState({ meetingFormKey: '' })
						window.location.href = './meetingList.html?scrollTo=' + res.meeting_id
					}
				} else {
					Alert(res.description || t('用户信息异常'), () => {
						if (meetingFormKey && serverInfo?.enable_room && user?.enable_kis) {
							unLockMeetingRoom(() => {
								removeRoomData()
								setTimeout(function () {
									window.location.href = '/meetingList.html'
								}, 200)
							}, true)
						}
					})
				}
			}
			//例会
			if (repeat) {
				if (useCreateContentStore.getState().state === 7 && meetingMoid) {
					//审批不通过修改例会
					fetchEditRegularMeeting(meetingMoid, data).then(callback)
				} else {
					//创建例会
					fetchSaveRegularMeeting(data).then(callback)
				}
				return
			}
			//会议
			if (meetingMoid) {
				//修改会议
				fetchEditMeeting(meetingMoid, data).then(callback)
			} else {
				//保存会议
				fetchSaveMeeting(data).then(callback)
			}
		})
	}

	const saveTpl = () => {
		fetchStatus(async () => {
			let m = Message.loading(t('正在保存，请稍候……'))
			let meetingMoid = useCreateContentStore.getState().meetingMoid
			let preKey = useCreateContentStore.getState().preKey
			let data = getAllParams() as SaveTemplateParams
			let res = meetingMoid ? await fetchEditTpl(meetingMoid, preKey, data) : await fetchSaveTpl(preKey, data)
			m.hide()
			if (res.success) {
				window.location.href = './template.html'
			} else {
				Alert(res.description || t('操作失败'))
			}
		})
	}

	return (
		<StyledWrap className="wrap">
			<div className="top-wrap">
				<Tab
					className="tab"
					type="button"
					data={tabData.filter((item) => !item.hidden)}
					value={tab}
					onChange={(e, v) => {
						update({ tab: v })
					}}
				/>
				<div className="options">
					{!isTemplate && (
						<CheckBox
							className="save-as-template"
							checked={_isSaveAsTemplate}
							onChange={(e, v) => {
								update({ _isSaveAsTemplate: v })
							}}
						>
							{t('保存为模板')}
						</CheckBox>
					)}
					<Button style={{ marginRight: 8 }} onClick={handelSave}>
						{t('保存')}
					</Button>
					<Button onClick={handleCancel}>{t('取消')}</Button>
				</div>
			</div>
			<div className="main-content">
				<div className="left-panel" ref={ref}>
					{tab === 'basic' && <BasicInfo />}
					{tab === 'params' && <MeetingParams />}
					{tab === 'vmp' && <MeetingVmp />}
					{tab === 'tvwall' && <MeetingTVWall />}
					{tab === 'poll' && <MeetingPoll />}
					{tab === 'mix' && <MeetingMix />}
					{tab === 'vl' && <MeetingLiveVideo />}
					{tab === 'dcs' && <MeetingDcs />}
					{tab === 'ai' && <MeetingAI />}
				</div>
				<div className="right-panel">
					<UserList />
				</div>
			</div>
			<AddMtDialog />
			<KdPreSettingDialog />
		</StyledWrap>
	)
}
